/*
 * Created on Jun 2, 2004
 */
package org.vectrics.recruiter.struts.tag;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.company.Company;
import org.vectrics.company.CompanySelectCriteria;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsTagSupport;

/**
 * @author mmoore
 */
public class CompanySelectorTag extends VectricsTagSupport {

	private static final long serialVersionUID = -7969514665321499145L;
	
	private String showBgColor = "false";
	private boolean alternateColorRow = false; 
	private String maxCompanyCount = "30";
	private int columnCount = 2;
	private String showCompanyLocation = "false";
	private String fontClass = "subFont";
	private String width = "100%";

	/**
	 * 
	 */
	public CompanySelectorTag() {
		super();
	}
	
	public String makeStartTag() {
		StringBuffer html = new StringBuffer();
		ArrayList columnData = new ArrayList();
		for (int i = 0; i < this.getColumnCount(); i++) {
			columnData.add(new ArrayList());
		}
		
		
		CompanySelectCriteria criteria = new CompanySelectCriteria();
		criteria.setVoidedType(CompanySelectCriteria.VOID_NO);
		criteria.setNoChildren(false);
        Set domains = CoreServiceLocator.getPersonService().findDomainsWithUserPrivilege(ThreadProperties.getPerson(), "job.view");
        criteria.setDomains(domains);
		List companies = CoreServiceLocator.getCompanyService().findCompanies(criteria, 0, 10);
		if ((companies.size() > 0) && (companies.size() < Integer.parseInt(this.maxCompanyCount))) {
			html.append("<br><h4>Companies</h4><h5>"
					+ "<i>Leaving all companies unchecked will give results from all companies</i></h5>");
			Table table = new Table();
			table.setWidth(width);
			
			Iterator iter = companies.iterator();
			while (iter.hasNext()) {
				Company company = (Company)iter.next();
				int column = findMostEmptyColumn(columnData);
				ArrayList columnCompanies = (ArrayList)columnData.get(column);
				columnCompanies.add(company);
				Collection children = CoreServiceLocator.getCompanyService().findChildCompanies(company.getId(), 0, 30);
				columnCompanies.addAll(children);
			}
			
			renderCompanyTable(columnData, table);
			html.append(table.toString());
		} else {
			html.append("");
		}
		return(html.toString());
	}
	
	
	private int findMostEmptyColumn(ArrayList columnData) {
		int column = 0;
		int minNum = ((ArrayList)columnData.get(0)).size();
		
		for (int i = 0; i < columnData.size(); i++) {
			int num = ((ArrayList)columnData.get(i)).size();
			if (num < minNum) {
				minNum = num;
				column = i;
			}
		}
		return(column);
	}
	
	
	private void renderCompanyTable(ArrayList columnData, Table table) {
		int rowCount = getNumberOfRows(columnData);
		for (int i = 0; i < rowCount; i++) {
			Row row = table.addRow();
			for (int j = 0; j < this.getColumnCount(); j++) {
				ArrayList companyColumn = (ArrayList)columnData.get(j);
				if (companyColumn.size() > i) {
					Company company = (Company)companyColumn.get(i);
					this.makeCompanySelector(row, company);
				} else {
					row.addCell();
				}
				if (j < this.getColumnCount() - 1) {
					Cell cell = row.addCell();
					cell.addElement("&nbsp;");
				};
				
			}
			
		}
	}

	
	private int getNumberOfRows(ArrayList columnData) {
		int maxNum = ((ArrayList)columnData.get(0)).size();
		
		for (int i = 0; i < columnData.size(); i++) {
			int num = ((ArrayList)columnData.get(i)).size();
			if (num > maxNum) {
				maxNum = num;
			}
		}
		return(maxNum);
	}
		
	private void makeCompanySelector(Row row, Company company) {
		String cellClass = null;
		if (this.hasBgColor()) {
			if (alternateColorRow) {
				cellClass = "formBg2";
				alternateColorRow = false;
			} else {
				cellClass = "formBg1";
				alternateColorRow = true;
			}
		} else {
			cellClass = null;
		}

		String companyName = company.getName();
		
		// TODO - remove indented
		boolean indented = false;
		//if (company.getParentId() != null) {
		//	Company parent = CompanyProvider.getInstance().findCompany(company.getParentId());
		//	if (parent != null) {
		//		companyName = parent.getName() + " - " + companyName;
		//	}
		//}
		
		if (indented) {
			Cell indentCell = row.addCell();
			indentCell.addElement("<img border=\"0\" src=\"" 
					 + this.getContextPath() +
					"/graphics/cleardot.gif\" width=\"15\" height=\"1\">");
		} 
		
		
		Cell nameCell = row.addCell();
		if (indented == false)
			nameCell.setColSpan(2);
		if (cellClass != null)
			nameCell.setClass(cellClass);
		String checkHtml = "<input type=\"checkbox\" name=\""
			+ "company_" + company.getId()
			+ "\" value=\"on\">";
		nameCell.addElement(checkHtml + "&nbsp;");
		
		nameCell.addElement(TextHelper.getFont(fontClass, companyName));

		log.debug("Display location name of selectable company");
		String locationName = null; 
		if ((company.getAddress() != null) && (company.getAddress().getCity() != null)) {
			locationName = "<i>" + company.getAddress().getCity();
			if (company.getAddress().getState() != null) {
				locationName += ", " 
					+ company.getAddress().getState();
			}
			locationName += "</i>";
			nameCell.addElement(TextHelper.getFont(fontClass, "<br>&nbsp;&nbsp;&nbsp;" + locationName));
		}
	}
	
	
	
/*	
	Iterator iter = companies.iterator();
	int cellNum = 0;
	Row row = null;
	while (iter.hasNext()) {
		if (cellNum == 0) {
			row = table.addRow();
		}
		Cell cell = row.addCell();
		cell.setVAlign("top");
		Table companyTable = new Table();
		cell.addElement(companyTable);
		Company company = (Company)iter.next();
		makeCompanySelector(companyTable, company, false);
		cellNum++;
		if (cellNum >= columnCount)
			cellNum = 0;
	}
	while (cellNum < columnCount) {
		if (row != null) {
			row.addCell();
		}
		cellNum++;
	}
	html.append(table.toString());
} else {
	html.append("");
}
return(html.toString());
}


private void makeCompanySelector(Table table, Company company, boolean indented) {
	String cellClass = null;
	if (this.hasBgColor()) {
		if (alternateColorRow) {
			cellClass = "formBg2";
			alternateColorRow = false;
		} else {
			cellClass = "formBg1";
			alternateColorRow = true;
		}
	} else {
		cellClass = null;
	}
	Row row = table.addRow();

	if (indented) {
		Cell indentCell = row.addCell();
		indentCell.addElement("<img border=\"0\" src=\"" 
				+ this.getContextPath() +
		"/graphics/cleardot.gif\" width=\"15\" height=\"1\">");
	} 

	Cell nameCell = row.addCell();
	if (indented == false)
		nameCell.setColSpan(2);
	if (cellClass != null)
		nameCell.setClass(cellClass);
	String checkHtml = "<input type=\"checkbox\" name=\""
		+ "company_" + company.getId()
		+ "\" value=\"on\">";
	nameCell.addElement(checkHtml + "&nbsp;");
	
	nameCell.addElement(TextHelper.getFont(fontClass, company.getName()));
	
	List children = CompanyProvider.getInstance().findChildCompanies(company.getId(), 0, 20);
	Iterator childIter = children.iterator();
	while (childIter.hasNext()) {
		Company child = (Company)childIter.next();
		makeCompanySelector(table, child, true);
	}
	
}
*/
	
	/**
	 * @return Returns the alternateColorRow.
	 */
	public boolean getAlternateColorRow() {
		return alternateColorRow;
	}
	/**
	 * @param alternateColorRow The alternateColorRow to set.
	 */
	public void setAlternateColorRow(boolean alternateColorRow) {
		this.alternateColorRow = alternateColorRow;
	}
	/**
	 * @return Returns the maxCompanyCount.
	 */
	public String getMaxCompanyCount() {
		return maxCompanyCount;
	}
	/**
	 * @param maxCompanyCount The maxCompanyCount to set.
	 */
	public void setMaxCompanyCount(String maxCompanyCount) {
		this.maxCompanyCount = maxCompanyCount;
	}
	/**
	 * @return Returns the columnCount.
	 */
	public int getColumnCount() {
		return columnCount;
	}
	/**
	 * @param columnCount The columnCount to set.
	 */
	public void setColumnCount(int columnCount) {
		this.columnCount = columnCount;
	}
	/**
	 * @return Returns the showCompanyLocation.
	 */
	public String getShowCompanyLocation() {
		return showCompanyLocation;
	}
	/**
	 * @param showCompanyLocation The showCompanyLocation to set.
	 */
	public void setShowCompanyLocation(String showCompanyLocation) {
		this.showCompanyLocation = showCompanyLocation;
	}
	
	private boolean hasBgColor() {
		return(this.showBgColor.toLowerCase().startsWith("tru"));
	}
	/**
	 * @param showBgColor The showBgColor to set.
	 */
	public void setShowBgColor(String showBgColor) {
		this.showBgColor = showBgColor;
	}

	/**
	 * @return Returns the showBgColor.
	 */
	public String getShowBgColor() {
		return showBgColor;
	}

	/**
	 * @return Returns the fontClass.
	 */
	public String getFontClass() {
		return fontClass;
	}

	/**
	 * @param fontClass The fontClass to set.
	 */
	public void setFontClass(String fontClass) {
		this.fontClass = fontClass;
	}

	/**
	 * @return Returns the width.
	 */
	public String getWidth() {
		return width;
	}

	/**
	 * @param width The width to set.
	 */
	public void setWidth(String width) {
		this.width = width;
	}

}
